package netty.nio.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @Author: zhangrongqing
 * @Date: 2020/1/9 18:18
 */
public class GroupChatServer {
    private Selector selector;

    private ServerSocketChannel listenChannel;

    private static int port = 9090;

    public GroupChatServer(){
        try{
            this.selector = Selector.open();
            this.listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(this.port));
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch(Exception e){

        }

    }

    //监听
    public void listen(){
        try {
            while (true){
                int count = selector.select(2000);
                if(count == 0){
                    System.out.println("无事件发生");
                    continue;
                }
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

                while (iterator.hasNext()){

                    SelectionKey selectionKey = iterator.next();

                    if(selectionKey.isAcceptable()){
                        //接受连接
                        SocketChannel accept = listenChannel.accept();
                        accept.configureBlocking(false);
                        accept.register(selector,SelectionKey.OP_READ);
                        System.out.println(accept.getRemoteAddress() + "上线了");
//                        sendMsgToOther(accept,"上线了");
                    }

                    if(selectionKey.isReadable()){
                        readClientMessage(selectionKey);
                    }
                }
                //删除key
                iterator.remove();
            }
        }catch (Exception e){

        }
    }

    public void readClientMessage(SelectionKey key){
        SocketChannel channel = null;
        try{
            channel = (SocketChannel)key.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int count = channel.read(byteBuffer);
            if(count <= 0 ){

            }else{
                String msg = new String(byteBuffer.array());
                System.out.println("from 客户端:"+msg);

                //向其他客户端转发消息
                sendMsgToOther(channel,msg);
            }
        }catch (IOException e){
            System.out.println("客户端下线");
            e.printStackTrace();
        }

    }

    //抓发消息
    private void sendMsgToOther(SocketChannel exceptChannel,String msg){
        //遍历channel
        for(SelectionKey selectionKey : selector.selectedKeys()){
            Channel channel = selectionKey.channel();

            //排除ServerSocketChannel
            if(channel instanceof SocketChannel && (!channel.equals(exceptChannel))) {
                SocketChannel targetChannel = (SocketChannel)channel;
                try {
                    targetChannel.write(ByteBuffer.wrap(msg.getBytes()));
                } catch (IOException e) {
                    try {
                        System.out.println(targetChannel.getRemoteAddress() + "下线了");
                        //取消注册
                        selectionKey.cancel();
                        //关闭通道
                        channel.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        new GroupChatServer().listen();
    }
}
